package com.example.redisson;

import jdk.nashorn.internal.runtime.logging.Logger;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.ListIterator;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

@Logger
public class RedissonLock {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(RedissonLock.class);

    private RedissonClient redissonClient;

    public RedissonLock(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    public <T> T synchronize(String lockName, Function<String, T> function) throws Exception {
        RLock rlock = redissonClient.getLock("lockName");
        boolean result = false;
        T apply;
        try {
            rlock.lock(); // 2.获取分布式锁
            result = rlock.tryLock(5L, 10L, TimeUnit.SECONDS);

            if (!result) {
                LOGGER.warn("get lock is null");
                throw new CustomException("获取锁失败");
            }

            apply = function.apply(lockName);

        } finally {
            // 3.释放锁
            if (null != rlock && result) {
                rlock.unlock();
            }
        }
        return apply;
    }

    @Autowired
    private RedissonLock redissonLock;

    public void lock(String[] args) throws Exception {
        redissonLock.synchronize("",(s)->{
            try {

                return "";
            } catch (Exception e){
                return e;
            }
        });
    }
}
